Explain the usage of [ 1] [: 1] [:: 1] and [n:: 1] in python in detail

  • 2021-11-02 01:23:56
  • OfStack

[m:] Represents item m+1 to last item in the list

[: n] Represents items 1 through n in the list

[-1] stands for going to the last item

[:-1] stands for all but the last

[::-1] stands for fetching in reverse order and fetching from back to front

[2::-1] Represents three numbers from 0 to 2 from the subscript, which are taken in reverse order

[1:] Represents the number taken from the subscript 1 to the last 1

Examples:


import numpy as np
a=np.random.rand(5)
print(a)
[ 0.64061262 0.8451399  0.965673  0.89256687 0.48518743]
 
print(a[-1]) ### Take the last 1 Elements 
[0.48518743]
 
print(a[:-1]) ###  Except in the end 1 Take all of them 
[ 0.64061262 0.8451399  0.965673  0.89256687]
 
print(a[::-1]) ###  Take elements from back to front (opposite) 
[ 0.48518743 0.89256687 0.965673  0.8451399  0.64061262]
 
print(a[2::-1]) ###  Take the subordinate subscript as 2 Element flip reading of 
[ 0.965673 0.8451399  0.64061262]

Another example:


a = np.array([[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]])
b = a[::-1, :]
print(b)
 
[[5 6 7 8 9]
 [0 1 2 3 4]]

Related articles: